package com.smile.commons;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.smile.commons.page.R;
import com.smile.commons.request.RequestIdUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class UnifiedResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        // 设置统一的JSON响应类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        if (body instanceof R) {
            ((R<?>) body).setRequestId(RequestIdUtils.get());
            return body;
        }

        if (body instanceof SaResult) {
            return body;
        }

        if (body instanceof String) {
            // 处理纯文本响应
            JSONObject json = JSONUtil.parseObj(body.toString());
            json.put("requestId", RequestIdUtils.get());
            return json;
        }
        R<Object> ok = R.ok(body);
        ok.setRequestId(RequestIdUtils.get());
        // 其他对象包装为统一响应
        return ok;
    }
}